var fs = require('fs');
var gulp = require('gulp');
var jsConcat = require('gulp-concat');
var config = require('./config');
var $ = require('cheerio');

// 工具方法
var util = {}

// 页面标记
util.TAG_CSS_REPLACE = /<!-- relpace-css\:.+ -->/gi;
util.TAG_HTML_REPLACE = /<!-- relpace-html\:.+ -->/gi;
util.TAG_JS_REPLACE = /<!-- relpace-js\:.+ -->/gi;
util.TAG_OPPOSITE_REPLACE = /(\.\.\/)+/gi;  


// 添加时间戳，之后应该改成MD5
util.replaceTimeStamp = function(tag) {
    if (tag) {
        return '"' + tag + '?_v=' + (new Date()).getTime() + '"';
    }else{
        return '';
    }
}

// 根据tag替换css文件
util.replaceStyleFile = function(tag, baseSearchPath) {
    var text = '';
    console.log('find css tag:' + tag);

    var fileexp = /\:(\S+\.\S+)/gi;

    var res = fileexp.exec(tag || '');

    if (res && res[1]) {
      console.log('replece css path:' + res[1]);
      try{
        text = fs.readFileSync(baseSearchPath + res[1], 'utf8');
      }catch(error){
        console.error('css file path error!');
      }
      
    }else{
      console.error('css file path error!');
    }

    return '<style>' + text + '</style>';
}

// 根据tag替换html文件: 如果是本地打包则直接替换为html代码
util.replaceHtmlFile = function(tag, baseSearchPath) {
    console.log('find html tag:' + tag);

    var fileexp = /\:(\S+\.\S+)\s+(\S+\.\S+)?/gi;

    var res = fileexp.exec(tag || '');

    var text = '';
        console.log('res :' + res);

    if (res && res[1]) {
        console.log('replece html path:' + baseSearchPath + res[1]);
            
        try{
            text = fs.readFileSync(baseSearchPath + res[1], 'utf8'); 
        }catch(error){
            console.error('read file fail : '+ error.message);
        }
          
    }else{
        console.error('html file path error!');
    }

    return text;
}

// 替换 js
util.replaceJs = function(tag, baseSearchPath){
    console.log('find js tag:' + tag);

	return util.replaceHtmlFile(tag, baseSearchPath);
}

util.logError = function (err) {
    console.error(JSON.stringify(err));
}

// gulp log 
util.logGulpEvents = function (gulpInst) {

    // gulpInst.on('err', function() {

    // });

    gulpInst.on('task_start', function(e) {
        console.log('Starting gulp task:' + e.task);
    });

    gulpInst.on('task_stop', function(e) {
        console.log('Finished ' + e.task + ' after ' + e.hrDuration);
    });

    gulpInst.on('task_err', function(e) {
        console.log(e.task + ' errored after ' + e.hrDuration);
    });

    gulpInst.on('task_not_found', function(err) {
        console.log('Task ' + err.task + ' is not found');
        process.exit(1);
    });
}


module.exports = util;
